/**
 * @Author: zkz
 * @Date: 2025/09/17 16:04
 * @Description: 发布文章页
 */
import { Card, Breadcrumb, Form, Button, Radio, Input, Upload, Space, Select, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link, useSearchParams } from 'react-router-dom';
import './index.scss';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { useEffect, useState } from 'react';
import { createArticleAPI, getArticleDetailAPI, updateArticleAPI } from '@/api/article';
import useChannel from '@/hooks/useChannel';
const { Option } = Select;

const Publish = () => {
	const [ form ] = Form.useForm();
	const { channelList } = useChannel();

	//提交文章
	const onFinish = async (values) => {
		// console.log(values);
		if (imageList.length !== imageType) return message.warning('封面类型与图片数量不匹配');
		const { title, channel_id, content } = values;
		//按照接口要求的格式处理表单数据
		const reqData = {
			title,
			channel_id,
			cover: {
				type: imageType,
				images: imageList.map((item) => {
					if (item.response) {
						return item.response.data.url;
					} else {
						return item.url;
					}
				}) //图片列表处理成接口要求的格式
			},
			content
		};
		//调用接口提交数据
		if (articleid) {
			// 更新文章
			const res = await updateArticleAPI(articleid, reqData);
			if (res.message === 'OK') {
				message.success('更新成功');
			} else {
				message.error('更新失败');
			}
		} else {
			// 新增发布文章
			const res = await createArticleAPI(reqData);
			if (res.message === 'OK') {
				message.success('发布成功');
				//重置表单与本地状态
				form.resetFields();
				setImageList([]);
				setImageType(1);
			} else {
				message.error('发布失败');
			}
		}
	};

	// 上传图片
	const [ imageList, setImageList ] = useState([]);
	const onChange = (value) => {
		setImageList(value.fileList);
	};

	// 选择封面类型
	const [ imageType, setImageType ] = useState(1);
	const onTypeChange = (type) => {
		setImageType(type.target.value);
	};

	const [ searchParams ] = useSearchParams();
	const articleid = searchParams.get('id');
	// 获取文章详情
	useEffect(
		() => {
			const getArticleDetail = async () => {
				const res = await getArticleDetailAPI(articleid);
				const data = res.data;
				const { cover } = data;
				form.setFieldsValue({
					...data,
					type: cover.type
				});
				setImageType(cover.type);
				setImageList(cover.images.map((item) => ({ url: item })));
			};

			if (articleid) {
				//获取文章详情
				getArticleDetail();
			}
		},
		[ articleid, form ]
	);

	return (
		<div className="publish">
			<Card
				title={
					<Breadcrumb
						items={[ { title: <Link to={'/'}>首页</Link> }, { title: articleid ? '编辑文章' : '发布文章' } ]}
					/>
				}
			>
				<Form
					form={form}
					labelCol={{ span: 4 }}
					wrapperCol={{ span: 16 }}
					initialValues={{ type: 1 }}
					onFinish={onFinish}
				>
					<Form.Item label="标题" name="title" rules={[ { required: true, message: '请输入文章标题' } ]}>
						<Input placeholder="请输入文章标题" style={{ width: 400 }} />
					</Form.Item>
					<Form.Item label="频道" name="channel_id" rules={[ { required: true, message: '请选择文章频道' } ]}>
						<Select placeholder="请选择文章频道" style={{ width: 400 }}>
							{/* value属性选中之后会自动收集起来作为提交接口的字段 */}
							{channelList &&
								channelList.map((item) => (
									<Option key={item.id} value={item.id}>
										{item.name}
									</Option>
								))}
						</Select>
					</Form.Item>
					<Form.Item label="内容" name="content" rules={[ { required: true, message: '请输入文章内容' } ]}>
						<ReactQuill className="publish-quill" theme="snow" placeholder="请输入文章内容" />
					</Form.Item>
					<Form.Item label="封面">
						<Form.Item name="type">
							<Radio.Group onChange={onTypeChange}>
								<Radio value={1}>单图</Radio>
								<Radio value={3}>三图</Radio>
								<Radio value={0}>无图</Radio>
							</Radio.Group>
						</Form.Item>
						{imageType > 0 && (
							<Upload
								listType="picture-card"
								showUploadList
								action={'http://geek.itheima.net/v1_0/upload'}
								name="image"
								maxCount={imageType}
								fileList={imageList}
								onChange={onChange}
							>
								<div style={{ marginTop: 8 }}>
									<PlusOutlined />
								</div>
							</Upload>
						)}
					</Form.Item>
					<Form.Item wrapperCol={{ offset: 4 }}>
						<Space>
							<Button size="large" type="primary" htmlType="submit">
								发布文章
							</Button>
						</Space>
					</Form.Item>
				</Form>
			</Card>
		</div>
	);
};

export default Publish;
